<template>
	<div>

		<div class="tool">
			<p style="">
				<el-date-picker style="display: block;width: calc(100% - 20px);" @change="changdata" v-model="query.data" :editable="false"
					type="date" placeholder="选择日期">
				</el-date-picker>
			</p>
		</div>
		<div class="tableitemss" style="position: fixed;height: 100%;width: 100%;top: 0;">
			<!-- 高德地图 -->
			<div id="container" style="height: 100%;"></div>
		</div>
		<p style="position: fixed;top:20%;right: 10px;transform: translateY(-50%);">
			<span v-if="runtype!='stop' && runtype!='end'" @click="runpo('stop')"
				style="display: block;width: 26px;height: 26px;background:  #ccc;border-radius: 50%;margin-bottom: 20px;overflow: hidden;">
				<i class="el-icon-video-pause"
					style="font-size: 22px;display: block;width: 22px;height: 22px;margin: 0 auto;padding-top: 2px;"></i>
			</span>
			<span v-else @click="runpo('run')"
				style="display: block;width: 26px;height: 26px;background:  #ccc;border-radius: 50%;margin-bottom: 20px;">
				<i class="el-icon-video-play"
					style="font-size: 22px;display: block;width: 22px;height: 22px;margin: 0 auto;padding-top: 2px;"></i>
			</span>
			<span @click="dialogVisible=true"
				style="display: block;width: 25px;height: 25px;background: #ccc;border-radius: 50%;margin-bottom: 20px;">
				<i class="el-icon-setting"
					style="font-size: 22px;display: block;width: 22px;height: 22px;margin: 0 auto;padding-top: 2px;"></i>
			</span>
		</p>
		<el-dialog
		  title="提示"
		  :visible.sync="dialogVisible"
		  width="92%">
		  <div>
			  <p style="padding: 0 20px;border-bottom: 1px solid #ccc;padding-bottom: 10px;">
				  <el-radio v-model="showquey.line" label="1">画线</el-radio>
				    <el-radio v-model="showquey.line" label="2">描点</el-radio>
				    <el-radio v-model="showquey.line" label="3">画线及描点</el-radio>
			  </p>
			  <div>
				  <el-checkbox-group v-model="showquey.load">
				      <el-checkbox label="复选框 A"></el-checkbox>
				      <el-checkbox label="复选框 B"></el-checkbox>
				      <el-checkbox label="复选框 c"></el-checkbox>
				    </el-checkbox-group>
			  </div>
		  </div>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="dialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
		  </span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		name: '',
		data() {
			const self = this;
			return {
				showquey:{
					line:1,
					load:[]
				},
				dialogVisible:false,
				query: {
					data: ''
				},
				zoom: 17,
				map: false,
				infoWindow: '',
				runmarker: false,
				runtype: '',
				list: [{
						lng: 109.45744048529967,
						lat: 36.49771311230842,
						title: '2021-10-1 10:10:10',
						pos: 'WIFI定位',
						name: 'FZD9322',
						num: '60%'
					},
					{
						lng: 109.45744048529967,
						lat: 36.5171311230842,
						title: '2021-10-2 10:10:10',
						pos: 'WIFI定位',
						name: 'FZD9322',
						num: '70%'
					},
					{
						lng: 109.467744048529967,
						lat: 36.49771311230842,
						title: '2021-10-3 10:10:10',
						pos: 'WIFI定位',
						name: 'FZD9322',
						num: '80%'
					},
					{
						lng: 109.467744048529967,
						lat: 36.60771311230842,
						title: '2021-10-3 10:10:10',
						pos: 'WIFI定位',
						name: 'FZD9322',
						num: '80%'
					},
				]
			};
		},
		created() {
			document.title = '设备轨迹';
			this.map && this.map.destroy();
			this.$nextTick(() => {
				try {
					this.map = new AMap.Map('container', {
						// center: [109.95744048529967, 36.49771311230842],
						center: [116.397428, 39.90923],
						zoom: this.zoom,
						resizeEnable: true,
						pitch: 40,
						// viewMode: '3D',
						// features: ['bg', 'road', 'building', 'point']
					})
					this.infoWindow = new AMap.InfoWindow({
						offset: new AMap.Pixel(0, -35),
					});
					var roadNetLayer = new AMap.TileLayer.RoadNet(); //网格
					// var satelliteLayer = new AMap.TileLayer.Satellite();//卫星
					this.map.add(roadNetLayer)
					// this.map.on('click', (e)=>{
					// 	this.showdata(e);
					// });
					setTimeout(()=>{
						this.addpoly();
					},1000)
				} catch (e) {
					this.$message.error('地图加载错误，请刷新重试!');
				}
				// this.map.add(satelliteLayer)
			})

		},
		components: {},
		computed: {},
		methods: {
			async showdata(e) {
				var lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];

				var address = await this.getpos(lnglat);
				// console.log(address)
				this.$message.info(address.address);
			},
			linkwei() {
				// if(JSON.stringify(this.$route.query).length == 2){
				// 	return this.$message.error('请先选择老人！');
				// }

				// if($route.query)
				this.$router.push({
					path: '/setposition',
					query: this.$route.query
				})
			},
			changdata(res) { //日期赛选器触发
				//res[1,2]1.val1,val2开始日期，结束日期
				// console.log(res[0].getTime())
			},
			async addmarker(o, show, type, icon) { //获取定位信息
				// 创建一个 Marker 实例：
				// this.remarker();
				// var icons = new AMap.Icon({
				//     size: new AMap.Size(40, 40),    // 图标尺寸
				//     image: '//vdata.amap.com/icons/b18/1/2.png',  // Icon的图像
				//     // imageOffset: new AMap.Pixel(0, -60),  // 图像相对展示区域的偏移量，适于雪碧图等
				//     imageSize: new AMap.Size(40, 40)   // 根据所设置的大小拉伸或压缩图片
				// });
				let address = await this.getpos([o.lng, o.lat]);
				// this.map.setZoom(this.zoom);
				// this.map.setCenter([109.55744048529967, 36.49771311230842]);
				// this.map.panTo([109.55744048529967, 36.49771311230842]);//平移
				var marker = new AMap.Marker({
					icon: icon ? icon : '',
					// icon:icons,
					position: new AMap.LngLat(o.lng, o.lat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
					title: address.address,
					// offset: new AMap.Pixel(-25, -30),
					extData: {
						type: 'marker',
						oneid: type ? type : 'marker'
					}
				});
				// marker.setLabel({
				//         offset: new AMap.Pixel(0, -3),  //设置文本标注偏移量
				//         content: "<div style='padding:0 10px' class='info'>2011-10-1 10:30</div>", //设置文本标注内容
				//         direction: 'top' //设置文本标注方位
				//     });
				// 将创建的点标记添加到已有的地图实例：
				let info = [];
				info.push(
					"<div style=\"padding:2px 0px 0px 0px;\"><h4 style='padding-bottom:5px;font-size:16px'>" + o
					.name + "</h4>"
				);
				info.push("<p class='input-item'>" + o.title + "</p>");
				info.push("<p class='input-item'>" + o.pos + "</p>");
				info.push("<p class='input-item'>电量 :" + o.num + "</p></div></div>");
				info.push("<p class='input-item'>地点 :" + address.address + "</p></div></div>");
				// console.log(this.map.getCenter())
				if (show) {
					setTimeout(() => {
						this.infoWindow.setContent(info.join(""));
						this.infoWindow.open(this.map, new AMap.LngLat(o.lng, o.lat));
					}, 200)
				}
				marker.on('click', (e) => {
					this.infoWindow.setContent(info.join(""));
					this.infoWindow.open(this.map, e.target.getPosition());
				})
				this.map.add(marker);
				return marker;
				// this.map.setFitView([marker],false,[100,100,100,100])
			},
			remarker(obj) { //删除定位信息
				// this.map.remove(this.marker);//清除单一
				// this.clearall();
				var marker = this.getover(obj);
				this.map.remove(marker);
				this.infoWindow.close();
			},
			clearall() { //清空地图所有覆盖物
				this.map.clearMap();
			},
			getover(obj) { //获取覆盖物
				var overlays = this.map.getAllOverlays();
				var arr = [];

				function istrue(o) {
					var ty = true;
					for (var j in obj) {
						var d = obj[j];
						if (o[j] != obj[j]) {
							ty = false;
							break;
						}
					}
					return ty;
				}
				if (!obj) {
					arr = overlays;
				} else {
					for (var i in overlays) {
						var o = overlays[i];
						var data = o.getExtData(); //extData
						if (istrue(data)) {
							arr.push(o);
						}
					}
				}
				// console.log(arr,obj)
				return arr;
			},
			async runpo() {
				var time = 8000;
				var idx = 1,
					_this = this;
					console.log(_this.runtype)
				if (_this.runtype == 'run') {
					this.runmarker.pauseMove();
					_this.runtype = 'stop';
					return;
				} else if (_this.runtype == 'stop') {
					this.runmarker.resumeMove();
					
					return;
				}
				this.remarker({
					type: 'marker',
					oneid: 'movemarker'
				});
				this.runmarker = await this.addmarker(this.list[0], true, 'movemarker', '');
				var movearr = [
					[this.list[idx - 1].lng, this.list[idx - 1].lat],
					[this.list[idx].lng, this.list[idx].lat]
				]
				moveimg()
				moveend();
				this.runmarker.moveAlong(movearr, time);
				function moveend(){
					_this.runmarker.on('moveend', async (e) => {
						console.log(idx,_this.list.length - 1)
						if (idx == _this.list.length - 1) {
							_this.runtype = 'end';
							idx = 1;
							return
						}
						idx++;
						var movearr = [
							[_this.list[idx - 1].lng, _this.list[idx - 1].lat],
							[_this.list[idx].lng, _this.list[idx].lat]
						]
					
						_this.remarker({
							type: 'marker',
							oneid: 'movemarker'
						});
						_this.runmarker = await _this.addmarker(_this.list[idx], true, 'movemarker', '');
						moveimg()
						moveend();
						_this.runmarker.moveAlong(movearr, time);
					});
				}
				function moveimg() {
					_this.runmarker.on('moving', (e) => {
						_this.runtype = 'run';
						let obj = e.target.getPosition();
						let info = [];
						info.push(
							"<div style=\"padding:2px 0px 0px 0px;\"><h4 style='padding-bottom:5px;font-size:16px'>" +
							_this.list[idx - 1].name + "</h4>"
						);
						info.push("<p class='input-item'>" + _this.list[idx - 1].title + "</p>");
						info.push("<p class='input-item'>" + _this.list[idx - 1].pos + "</p>");
						info.push("<p class='input-item'>电量 :" + _this.list[idx].num + "</p></div></div>");
						_this.infoWindow.setContent(info.join(""));
						_this.infoWindow.open(_this.map, obj);
					});
				}
				// this.remarker({type:'marker',oneid:'movemarker'});
				// this.addmarker(this.list[idx],true,'movemarker','');
			},
			async addpoly() { //获取轨迹图
				// 折线的节点坐标数组，每个元素为 AMap.LngLat 对象
				this.clearall();
				var polylinearr = this.list;
				var path = [
					// new AMap.LngLat(109.45744048529967,36.49771311230842),
					// new AMap.LngLat(109.45744048529967,36.5171311230842),
					// new AMap.LngLat(109.467744048529967,36.49771311230842),
				];
				this.addmarker(polylinearr[0], false, false, '//vdata.amap.com/icons/b18/1/2.png');
				this.addmarker(polylinearr[polylinearr.length - 1], false, false,
					'//vdata.amap.com/icons/b18/1/2.png');
				for (var i in polylinearr) {
					let o = polylinearr[i];
					path.push(new AMap.LngLat(o.lng, o.lat));
					// let marker = new AMap.Marker({
					// 	position: path[i],
					// 	map: this.map,
					// 	title: o.title,
					// 	extData:{
					// 		type:'marker',
					// 		oneid:'polyline'
					// 	}
					// });
					// let address = await this.getpos(path[i]);
					// let info = [];
					// info.push(
					// 	"<div style=\"padding:2px 0px 0px 0px;\"><h4 style='padding-bottom:5px;font-size:16px'>"+o.name+"</h4>"
					// 	);
					// info.push("<p class='input-item'>" + o.title + "</p>");
					// info.push("<p class='input-item'>" + o.pos + "</p>");
					// info.push("<p class='input-item'>电量 :" + o.num + "</p></div></div>");
					// info.push("<p class='input-item'>地点 :" + address.address + "</p></div></div>");
					// marker.on('click', (e) => {
					// 	this.infoWindow.setContent(info.join(""));
					// 	this.infoWindow.open(this.map, e.target.getPosition());
					// });
					// // marker.emit('click', {target: marker});
					// this.map.add(marker);

				}
				// this.map.setZoom(this.zoom);
				// this.map.setCenter(path[0]);
				// 创建折线实例
				var polyline = new AMap.Polyline({
					path: path,
					borderWeight: 2, // 线条宽度，默认为 1
					showDir: true,
					strokeWeight: 10,
					dirColor: '#fff',
					strokeColor: 'red', // 线条颜色
					lineJoin: 'round', // 折线拐点连接处样式
					extData: {
						type: 'polyline',
						oneid: 'polyline'
					}
				});
				// 将折线添加至地图实例
				this.map.add(polyline);
				this.map.setFitView([polyline], false, [101, 102, 110, 110])
				this.runpo();
			},
			starts() {
				var map = this.map;
				var marker, lineArr = [
					[116.478935, 39.997761],
					[116.478939, 39.997825],
					[116.478912, 39.998549],
					[116.478912, 39.998549],
					[116.478998, 39.998555],
					[116.478998, 39.998555],
					[116.479282, 39.99856],
					[116.479658, 39.998528],
					[116.480151, 39.998453],
					[116.480784, 39.998302],
					[116.480784, 39.998302],
					[116.481149, 39.998184],
					[116.481573, 39.997997],
					[116.481863, 39.997846],
					[116.482072, 39.997718],
					[116.482362, 39.997718],
					[116.483633, 39.998935],
					[116.48367, 39.998968],
					[116.484648, 39.999861]
				];
				marker = new AMap.Marker({
					map: map,
					position: [116.478935, 39.997761],
					icon: "https://webapi.amap.com/images/car.png",
					offset: new AMap.Pixel(-26, -13),
					autoRotation: true,
					angle: -90,
				});
				// 绘制轨迹
				marker.on('moving', function(e) {
					// console.log(e.target.getPosition());
					let obj = e.target.getPosition();
					map.setCenter([obj.lng, obj.lat]);
				});
				var polyline = new AMap.Polyline({
					map: map,
					path: lineArr,
					showDir: true,
					strokeColor: "#28F", //线颜色
					// strokeOpacity: 1,     //线透明度
					strokeWeight: 6, //线宽

					// strokeStyle: "solid"  //线样式
				});
				polyline.on('click', (e) => {
					console.log(e)
				})
				map.setFitView([polyline]);
				marker.moveAlong(lineArr, 500);
			},
			repoly() { //删除轨迹图
				var polyline = this.getover({
					type: 'polyline'
				});
				var marker = this.getover({
					type: 'marker',
					oneid: 'polyline'
				});
				this.map.remove(polyline);
				this.map.remove(marker);
				this.infoWindow.close();
			},
			getpos(lnglat) { //根据经纬度获取详细信息
				return new Promise((resolve) => {
					AMap.plugin('AMap.Geocoder', function() {
						var geocoder = new AMap.Geocoder({
							// city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode 
							city: '010'
						})
						geocoder.getAddress(lnglat, function(status, result) {
							if (status === 'complete' && result.info === 'OK') {
								// result为对应的地理位置详细信息 
								// console.log(result)
								resolve({
									address: result.regeocode.formattedAddress
								});
							}
						})
					})
				});
			},
			getlnglat(str) { //根据纤细地址获取经纬度
				return new Promise((resolve) => {
					AMap.plugin('AMap.Geocoder', function() {
						var geocoder = new AMap.Geocoder({
							// city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode 
							city: '010'
						})
						geocoder.getLocation(str, function(status, result) {
							if (status === 'complete' && result.info === 'OK') {
								// result中对应详细地理坐标信息
								resolve({
									address: result.geocodes[0].location,
									obj: result
								})
							}
						})
					})
				});
			},
			getdata() {

			},
		},
		watch: {
			collapses() {},
			$route(f, t) {
				this.clearall();
				// console.log(f, t)
			}
		},
		destroyed() {
			// console.log('closre')
			this.clearall();
			this.map && this.map.destroy();
		},
		mounted() {
			// this.addmarker()
		}
	};
</script>
<style type="text/css">
	.amap-marker-label {
		border: 0;
		/* background-color: transparent; */
		/*  */
	}
	.el-checkbox{
		display: block;
		overflow: hidden;
		margin: 10px 0;
		border-bottom: 1px solid #ccc;
		padding: 0px 20px;
		padding-bottom: 10px;
	}
	.el-checkbox__inner::after{
		left: 7px;
		width: 4px;
		height: 9px;
		top: 2px;
	}
	.el-checkbox__input.is-checked+.el-checkbox__label{
		color: #fff;
	}
	.el-checkbox__inner{
		width: 20px;
		height: 18px;
	}
	.el-checkbox__label{
		color: #fff;
		float: left;
		padding: 0;
	}
	.el-checkbox__input{
		float: right;
	}
	.el-dialog__body{
		padding: 15px 0px;
		padding-bottom: 15px;
	}
	.el-radio{
		color: #fff;
	}
	.el-dialog{
		background: #1a458c;
		color: #fff;
	}
	.el-dialog__headerbtn .el-dialog__close{
		color: #fff;
	}
	.el-dialog__header{
		padding-top: 15px;
		border-bottom:1px solid #ccc;
	}
	.el-dialog__headerbtn{
		top: 15px;
	}
	.el-dialog__title{
		color: #fff;
	}
	.info {
		position: relative;
		top: 0;
		right: 0;
		min-width: 0;
	}

	.el-dialog--center {
		min-width: 600px;
	}

	.el-table__body-wrapper {
		/* background:rgba(242, 242, 242, 1) */
	}
</style>
<style scoped>
	.tool {
		/* background-color: #fff; */
		padding: 5px 10px;
		border-top: 1px solid #ccc;position: fixed;top: 0;width: 100%;overflow: hidden;z-index: 1;
	}

	.tool>* {}

	.tool>p {}
</style>
